package tzhomestudio.framework.shared.utils;

import tzhomestudio.framework.shared.exceptions.NoAttemptsException;

/**
 * @author Timur Zolotuhin (e-mail: tzolotuhin@gmail.com)
 */
public abstract class RunAttemptsWithTimeout {
    private int sleepTimeout;
    private int attempts;

    protected Object returnValue;

    public RunAttemptsWithTimeout(int attempts, int sleepTimeout) {
        this.attempts = attempts;
        this.sleepTimeout = sleepTimeout;
    }

    public abstract boolean attempt();

    public void run() {
        for (int i = 0; i < attempts; i++) {
            try {
                boolean re = attempt();
                if (re) return;
            } catch (Throwable ex) {
                //FrameworkMainServiceHelper.logger.printDebug("Attempt: " + i + " failed", ex);
            }

            try {
                Thread.sleep(sleepTimeout);
            } catch (Throwable ex) {
                //FrameworkMainServiceHelper.logger.printDebug("Please, ignore this exception.", ex);
            }
        }

        throw new NoAttemptsException("No attempts");
    }

    public Object getReturnValue() {
        return returnValue;
    }
}
